package initialize

import (
	"encoding/json"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"goods_srv/global"
)

func GetSystemConfig() bool {
	viper.AutomaticEnv()
	getString := viper.GetString("SHOP_MODE")
	if getString == "dev" {
		return false
	} else if getString == "prod" {
		return true
	}
	return false
}
func InitConfig() {
	v := viper.New()
	flag := GetSystemConfig()
	if flag {
		v.SetConfigFile(fmt.Sprintf("%s/config/prod_config.yaml", global.RootPath))
	} else {
		v.SetConfigFile(fmt.Sprintf("%s/config/dev_config.yaml", global.RootPath))
	}
	err := v.ReadInConfig()
	if err != nil {
		zap.S().Panic(err)
	}
	err = v.Unmarshal(&global.ServerConfig)
	if err != nil {
		zap.S().Panic(err)
	}
	go func() {
		v.OnConfigChange(func(in fsnotify.Event) {
			err = v.Unmarshal(&global.ServerConfig)
			if err != nil {
				zap.S().Panic(err)
			}
		})
		v.WatchConfig()
	}()
	//连接nacos
	InitNacos()
}
func InitNacos() {
	//create clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         global.ServerConfig.NacosConfig.Namespace, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              global.ServerConfig.NacosConfig.LogDir,
		CacheDir:            global.ServerConfig.NacosConfig.CacheDir,
		LogLevel:            global.ServerConfig.NacosConfig.LogLevel,
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      global.ServerConfig.NacosConfig.IpAddr,
			ContextPath: "/nacos",
			Port:        uint64(global.ServerConfig.NacosConfig.ServerPort),
			Scheme:      "http",
			GrpcPort:    uint64(global.ServerConfig.NacosConfig.ServerGroupPort),
		},
	}
	client, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	if err != nil {
		zap.S().Panic(err)
	}
	content, err := client.GetConfig(vo.ConfigParam{
		DataId: global.ServerConfig.NacosConfig.DataId,
		Group:  global.ServerConfig.NacosConfig.Group})
	err = json.Unmarshal([]byte(content), &global.ServerConfig)
	if err != nil {
		zap.S().Panic(err)
	}
}
